<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="search">
				<el-form-item>
					<el-input v-model="search.key" placeholder="高级查询"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="queryData" class="el-icon-zoom-in">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd" class="el-icon-plus">新增</el-button>
          <el-button type="danger"  @click="batchRemove" :disabled="this.sels.length===0" class="el-icon-delete">批量删除</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="pageInfo.data" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="角色名称" width="150" sortable >
			</el-table-column>
      <el-table-column prop="sn" label="角色sn" width="200" sortable >
      </el-table-column>
      <el-table-column label="操作" width="280">
				<template scope="scope">
					<el-button size="small" plain @click="handleSave(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" plain size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="handleRole(scope.$index, scope.row)">授权</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--分页工具条-->
		<el-col :span="24" class="toolbar">
      <!--
        el-pagination 表示分页
        @size-change 每页跳数变化时候会触发的方法
        @current-change 当前页数改变的时候
        :current-page 绑定当前页的数据
        :page-sizes="[100, 200]  每页多少调的选择
        :page-size="100"  每页的条数
        :total="400" 总数
      -->
      <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="search.currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="100"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.total"
      style="float:right"
      >
      </el-pagination>
		</el-col>
    <!-- 授权界面-->
    <el-dialog title="授权" :visible.sync="roleFormVisible" :close-on-click-modal="false">
      <el-form :model="roleForm" label-width="80px"  ref="addForm">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.role.name" disabled auto-complete="off"></el-input>
        </el-form-item>

        <!--
          :props="props" 定义前端显示的数据 与 对象 属性是匹配的
          :data="data" 绑定数据源
          default-expand-all 默认展开
          ref="tree" 给树形控件取一个名字
        -->
        <el-form-item label="权限" prop="name">
          <el-tree
              :props="props"
              :data="data"
              default-expand-all
              node-key="id"
              ref="tree"
              show-checkbox
          >
          </el-tree>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="roleFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="addAuth" >提交</el-button>
      </div>
    </el-dialog>

    <!--新增/修改界面-->
		<el-dialog title="新增" :visible.sync ="saveFormVisible" :close-on-click-modal="false">
			<el-form :model="saveForm" label-width="80px"  ref="addForm">
				<el-form-item label="角色名称" prop="name">
					<el-input v-model="saveForm.name" auto-complete="off"></el-input>
				</el-form-item>
        <el-form-item label="角色sn" prop="sn">
        <el-input v-model="saveForm.sn" auto-complete="off"></el-input>
      </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="saveFormVisible = false" plain >取消</el-button>
				<el-button type="primary" @click.native="addSubmit">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
        roleFormVisible:false,
        roleForm:{
          role:{
            id:null,
            name:""
          },
          permissionList:[]
        },
        props:{
          label: "name",
          children:"children"
        },
        data:[],
        deptTree: [],
        employees: [],
        search: {
					key: '',
          pageSize: 7,
          currentPage: 1
				},
				pageInfo:{
          data: [] ,
          total: 0,
        },
        page: 1,
				listLoading: false,
				sels: [], //列表选中列

        saveFormVisible : false,
        saveForm : {
          id : null,
          name : "",
          sn :""
        }
			}
		},
		methods: {
		  //授权界面的提交按钮方法
      addAuth(){
      // 根据Node this.$refs.tree.getCheckedNodes();
        this.roleForm.permissionList = this.$refs.tree.getCheckedNodes();
      // 根据Key this.$refs.tree.getCheckedKeys()
      //   log(this.$refs.tree.getCheckedKeys())
        // 发送请求
        this.$http.post("/role/roleAuth",this.roleForm)
            .then(res=>{
              res = res.data;
              if(res.success){
                this.$message({type:"success",message:"授权成功"});
                this.roleFormVisible = false;
              }
            })
            .catch(res=>{})
      },
      // 根据角色的id 查询 角色所对应的权限方法
      queryAuthByRoleId(){
        //发送请求 (注意需要传入参数)
        this.$http.post("/role/roleAuth/"+this.roleForm.role.id)
            .then(res=>{
              res = res.data;
              if(res.success){
                var ids = res.data;
                this.$refs.tree.setCheckedKeys(ids);
              }
            })
            .catch(res=>{})
      },
		  //权限树的方法
      getTree(){
        //发送请求
        this.$http.get("/permission/deptTree")
            .then(res=>{
              res = res.data;
              if(res.success){
                this.data = res.data;
                this.queryAuthByRoleId();  //根据角色的id 查询 角色所对应的权限
              }
            })
            .catch(res=>{})
      },
		  //授权按钮点击方法
      handleRole(index,row){
        this.roleFormVisible = true;// 这是弹框
        this.roleForm.role = row
        this.getTree(); // 调用权限树方法
        // 回显数据 (有两种方法) 回显和 设置都有2中方案
        /*
             一种是通过 node:    node的回显有点麻烦  需要查询 该角色所有的 权限信息
             一种是通过 key:     如果通过key 不管是设置还是获取都要有 node-key属性
                               但是如果通过key 回显会简单一点 只需要 权限的id
         */
      },
		  //获取上级部门树方法
      getDeptTree(){
        //发送请求
        this.$http.get("/role/deptTree")
            .then(res=>{
              res = res.data;
              if(res.success){
                this.deptTree = res.data;
              }
            })
            .catch(res=>{})
      },
		  //部门管理员方法
      getManagers(){
        //发送请求
        this.$http.get("/employee")
        .then(res=>{
          res = res.data;
          if(res.success){
            this.employees = res.data;
          }
        })
        .catch(res=>{})
      },
		  //点击新增方法
      handleAdd(){
        this.saveFormVisible = true;
        //清空数据
        this.saveForm = {
          id : null,
              name : "",
              intro :"",
              manager:{
            id : "",
            username: ""
          },
          parent:{
            id : null,
            name : "",
          },
          state : ""
        },
        this.getManagers();
        //调用上级部门树的方法
        this.getDeptTree();
      },
		  //点击查询方法
      queryData(){
        this.search.currentPage = 1;
        this.getRole();
      },
      //每页跳数变化时候会触发的方法
      handleSizeChange(value){
			  this.search.pageSize = value;
			  this.getRole();
      },
			handleCurrentChange(val) {
				//val 当前页的页数
        this.search.currentPage = val;
				this.getRole();
			},
			//获取用户列表
			getRole() {
				this.listLoading = true;
				this.$http.post("/role",this.search)
        .then(res=>{
          this.listLoading = false;
          res = res.data
          if (res.success){
            // this.role = res.data.data;
            // this.total = res.data.data;
            this.pageInfo = res.data;
          }
          this.getDeptTree();
        })
        .catch(res=>{
        })
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					this.$http.delete("/role/"+row.id)
					.then(res=>{
            res = res.data;
            this.listLoading = false;
            if (res.success){
              this.$message({type:"success",message:"删除成功"})
            }else {
              this.$message.error("删除失败"+res.msg);
            }
            this.search.currentPage = 1;
            this.getRole();
          })
          .catch(res=>{

          })

				}).catch(() => {

				});
			},
			//显示新增/修改界面
			handleSave: function (index,row) {
				this.saveFormVisible = true;
        this.saveForm = JSON.parse(JSON.stringify(row)); //回显数据
        var split = row.path.split("/");//此时需要自己id和上级部门的id、可根据path去获取上级部门
        var data = [];
        for (let i = 1; i < split.length-1; i++) {
          data.push(Number.parseInt(split[i]));
        }
        this.saveForm.parent = data;
        if (!row.parent){
            this.saveForm.parent = {
              id:null,
              name : ""
          }
        }
        if (!row.manager){
          this.saveForm.manager = {
            id:null,
            username : ""
          }
        }
        this.getManagers();
        //调用上级部门树的方法
        this.getDeptTree();
        this.getRole();
			},
			//新增/修改
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							let para = Object.assign({}, this.saveForm);
							var parent = para.parent
              if (parent.length >= 0){
                if (parent.length == 0){
                  para.parent = { id : null, name: ""}
                }else {
                  para.parent = { id:parent[parent.length-1],name: ""}
                }
              }
              //发送请求
              this.$http.put("/role",para)
              .then(res=>{
                this.saveFormVisible = false;
                this.$message({type:"success",message:"保存成功"});
                this.getRole(); //刷新页面
              })
              .catch(res=>{})
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id)
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
          // 发送请求
          this.$http.patch("/role",ids)
              .then(res=>{
                res = res.data;
                this.listLoading = false;
                if (res.success){
                  this.$message({type:"success",message:"删除成功"})
                }else {
                  this.$message.error("删除失败"+res.msg);
                }
                this.search.currentPage = 1;
                this.getRole();
              })
              .catch(res=>{})
				}).catch(() => {});
			}
		},
		mounted() {
			this.getRole();
		}
	}
</script>

<style scoped>

</style>